//
//  TPProgressHUD.m
//  TPProgressHUDDemo
//
//  Created by 谭鹏 on 2017/7/20.
//  Copyright © 2017年 谭鹏. All rights reserved.
//


#import "TPProgressHUD.h"
#import <Masonry.h>
#import <ImageIO/ImageIO.h>
@interface TPProgressHUD()
#pragma mark - view
@property UIView * mainView;//主view
@property UIView * iconContainer;//图标容器
@property UIView * titleContainer;//提示字段容器
@property UIView * extendedContainer;//扩展容器：如text等
@property UIView * btnsContainer;//按钮容器
#pragma mark - para
@property TPProgressHUD_mainViewType mainViewType;//mainView类型
    @property CGFloat mainView_cornerRadiu;
    @property UIColor * mainView_bgColor;
@property TPProgressHUD_iconViewType iconViewType;//图标类型
@property NSMutableAttributedString * title,* subtitle;//提示语
@property NSArray <NSMutableAttributedString *> * btnTitles;
@property BOOL btnsIsVertical;//btns 是否垂直排列

@end

//const NSInteger BtnTag_ok     = 1000;
//const NSInteger BtnTag_cancel = 1001;

@implementation TPProgressHUD
- (void)setup
{
    
    if (self) {
        
        [self setupMainView];
        [self setupModuleViews];
        
        

        
    //最后presnt显示时运行
        //添加组件
            //[self addModuleViews];
        //layout
            //[self layoutModueViews];
        
        
        
        
       
    }
}
#pragma mark - MainView
- (void)setupMainView{
//    self.backgroundColor = [UIColor color]
    
    _mainView = [UIView new];
    [self addSubview: _mainView];
    _mainView.layer.cornerRadius = 5;
    _mainView.backgroundColor = [UIColor whiteColor];
    _mainView.clipsToBounds = YES;
}

- (void)setMainViewActions{
    
    UITapGestureRecognizer * tapGR = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapBgView:)];
    [self addGestureRecognizer:tapGR];
}


#pragma mark - ModuleView
- (void)setupModuleViews{
    //初始化组件
    [self initModuleViews];
    [self addModuleViews];
    [self layoutModueViews];
    
}

- (void)initModuleViews
{

            _iconContainer = [UIView new];
            _titleContainer = [UIView new];
            _extendedContainer = [UIView new];
            _btnsContainer = [UIView new];
            
}
- (void)addModuleViews{
//    [UIApplication.sharedApplication.keyWindow addSubview:self];
    
   
        [_mainView addSubview:_iconContainer];
        [_mainView addSubview:_titleContainer];
        [_mainView addSubview:_extendedContainer];
        [_mainView addSubview:_btnsContainer];
}
- (void)layoutModueViews{
    [self setFrame:[UIScreen mainScreen].bounds];
//    [self mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.size.mas_equalTo(UIScreen.mainScreen.bounds.size);
//    }];
    [_mainView mas_makeConstraints:^(MASConstraintMaker *make) {
       make.center.mas_equalTo(UIScreen.mainScreen.bounds.size);
        //make.width.mas_equalTo(200);
       
    }];
        [_iconContainer mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(_mainView).offset(0);
            make.left.right.mas_equalTo(_mainView);
        }];
        [_titleContainer mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(_iconContainer.mas_bottom);
            make.left.right.mas_equalTo(_mainView);
        }];
        [_extendedContainer mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(_titleContainer.mas_bottom);
            make.left.right.mas_equalTo(_mainView);
        }];
        [_btnsContainer mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(_extendedContainer.mas_bottom).offset(0);
            make.left.right.mas_equalTo(_mainView);
            make.bottom.mas_equalTo(_mainView);
        }];
    
}
- (void)setModueViewActions{
    
}
#pragma mark - DetailModule
//设备图标
- (void)setupIconContainerWithIconType:(TPProgressHUD_iconViewType)iconType{
    UIImage * image = nil;
    switch (iconType) {
        case TPProgressHUD_iconViewType_none:
        {
        }
            break;
        case TPProgressHUD_iconViewType_warning:
        {
            image = [UIImage imageNamed:@"warning"];
        }
            break;
        case TPProgressHUD_iconViewType_error:
        {
            image = [UIImage imageNamed:@"error"];
        }
            break;
        case TPProgressHUD_iconViewType_sucess:
        {
            image = [UIImage imageNamed:@"sucess"];
        }
            break;
            
        default:
            break;
    }
    
    if (image) {
        UIImageView * imageView = [[UIImageView alloc]initWithImage:image];
        [_iconContainer addSubview: imageView];
        [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
           make.centerX.mas_equalTo(_iconContainer);
            make.top.mas_equalTo(_iconContainer).offset(25);
            make.bottom.mas_equalTo(_iconContainer).offset(0);
        }];
        
    }
}
//设置提示语 title subtitle
- (void)setupTitleContainerWithTitle:(NSMutableAttributedString *)attrTitle subtitle:(NSMutableAttributedString *)attrSubtitle{
    UILabel * titleLabel = [UILabel new];
    UILabel * subtitleLabel = [UILabel new];
    [_titleContainer addSubview:titleLabel];
    [_titleContainer addSubview:subtitleLabel];
    
    if (attrTitle) {
        titleLabel.textAlignment = NSTextAlignmentCenter;
        titleLabel.attributedText = attrTitle;
    }
    
    if (attrSubtitle) {
        subtitleLabel.textAlignment = NSTextAlignmentCenter;
       subtitleLabel.attributedText = attrTitle;

    }
    
    
    
    
        [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.mas_equalTo(_titleContainer);
            make.top.mas_equalTo(_titleContainer).offset(25);
            make.width.mas_equalTo(200).priorityMedium();
        }];
    
    
    
        [subtitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(titleLabel.mas_bottom).offset(10);
            make.left.right.mas_equalTo(_titleContainer);
            make.bottom.mas_equalTo(_titleContainer).offset(0);
        }];
        
    
    
    
}
//设置 按钮，横向竖向分布
- (void)setupBtnsContainerWithCancelBtnTitle:(NSAttributedString *)cancelBtnTitle okBtnTitle:(NSAttributedString *)okBtnTitle  otherBtnTitles:(NSArray<NSMutableAttributedString *> *)otherTitles isVertical:(BOOL)isVertical{

    NSArray * btnTitles = [[[[NSArray new] arrayByAddingObject:cancelBtnTitle] arrayByAddingObjectsFromArray:otherTitles] arrayByAddingObject:okBtnTitle];
    CGFloat height = 75;
    UIButton * lastBtn = nil;
    //
    for (NSMutableAttributedString * attrTitle in btnTitles) {
        UIButton * btn = [UIButton new];
        
        [_btnsContainer addSubview:btn];
        [btn setAttributedTitle:attrTitle forState:UIControlStateNormal];
        [btn mas_makeConstraints:^(MASConstraintMaker *make) {
            if (!lastBtn) {
                make.top.left.mas_equalTo(_btnsContainer);
                make.height.mas_equalTo(height);
            }else{
                if (isVertical) {
                    make.top.mas_equalTo(lastBtn.mas_bottom);
                    make.left.mas_equalTo(lastBtn);
                }else{
                    make.top.mas_equalTo(lastBtn);
                    make.left.mas_equalTo(lastBtn.mas_right);
                }
                
                make.height.mas_equalTo(lastBtn);
                make.width.mas_equalTo(lastBtn);
            }
        }];
        lastBtn = btn;
        
    }
    
    
   
        
        __weak TPProgressHUD * weakSelf = self;
        self.willDismissAlertViewTapBtnBlock = ^BOOL(UIButton *btn) {
            if (cancelBtnTitle && weakSelf.willDismissAlertViewTapBtnCancelBlock && _btnsContainer.subviews.firstObject == btn) {
                return  weakSelf.willDismissAlertViewTapBtnCancelBlock();
            }else if (okBtnTitle && weakSelf.willDismissAlertViewTapBtnOkBlock && _btnsContainer.subviews.lastObject == btn) {
                return  weakSelf.willDismissAlertViewTapBtnOkBlock();
            }else if(otherTitles && otherTitles.count && weakSelf.willDismissAlertViewTapBtnOtherBlock){
                return weakSelf.willDismissAlertViewTapBtnOtherBlock();
            }else{
                return YES;
            }
          
        };
    
    [_btnsContainer.subviews.lastObject mas_makeConstraints:^(MASConstraintMaker *make) {
       make.bottom.right.mas_equalTo(_btnsContainer);
    }];
    
    
    for (UIButton * btn in _btnsContainer.subviews) {
        [btn addTarget:self action:@selector(tapBtn:) forControlEvents:UIControlEventTouchUpInside];
    }
    
}
#pragma mark - public
- (void)presentWithAnimated:(BOOL)animated{
    
    [UIApplication.sharedApplication.keyWindow addSubview:self];
    
}
- (void)dismissWithAnimated:(BOOL)animated{
    [self removeFromSuperview];
}

//无btn简单提示框,默认点击bg消失
- (instancetype)initWithString:(NSString*)string iconViewType:(TPProgressHUD_iconViewType)iconViewType
{
    self = [super init];
    if (self) {
        
        [self setup];
        [self setMainViewActions];
        [self setupIconContainerWithIconType:iconViewType];
            NSMutableAttributedString * str = [self attrStringWithString:string color:[UIColor blackColor] font:[UIFont systemFontOfSize:18]];
        [self setupTitleContainerWithTitle:str subtitle:nil];

    }
    return self;
}




//有btn简单提示框,默认点击bg消失
- (instancetype)initWithString:(NSString*)string iconViewType:(TPProgressHUD_iconViewType)iconViewType cancelBtnAttrTitle:(NSAttributedString *)cancelBtnAttrTitle okBtnAttrTitle:(NSAttributedString *)okBtnAttrTitle  otherBtnAttrTitles:(NSArray<NSMutableAttributedString *> *)otherAttrTitles isVertical:(BOOL)isVertical{
    self = [self initWithString:string iconViewType:iconViewType];
    if (self) {
        [self setupBtnsContainerWithCancelBtnTitle:cancelBtnAttrTitle okBtnTitle:okBtnAttrTitle otherBtnTitles:otherAttrTitles isVertical:YES];
    }
    return  self;
}
//有btn简单提示框,默认点击bg消失
- (instancetype)initWithString:(NSString*)string iconViewType:(TPProgressHUD_iconViewType)iconViewType cancelBtnTitle:(NSString *)cancelBtnTitle okBtnTitle:(NSString *)okBtnTitle  otherBtnTitles:(NSArray<NSString *> *)otherTitles isVertical:(BOOL)isVertical{
    
    self = [self initWithString:string iconViewType:iconViewType];
    if (self) {
        NSAttributedString * attrCancel = [self attrStringWithString:cancelBtnTitle color:[UIColor blackColor] font:[UIFont systemFontOfSize:18]];
        NSAttributedString * attrOk = [self attrStringWithString:okBtnTitle color:[UIColor blackColor] font:[UIFont systemFontOfSize:18]];
        NSMutableArray * attrOtherTitles = [NSMutableArray new];
        for (NSString * title in otherTitles) {
            [attrOtherTitles addObject:[self attrStringWithString:title color:[UIColor blackColor] font:[UIFont systemFontOfSize:18]]];
        }
        
        [self setupBtnsContainerWithCancelBtnTitle:attrCancel okBtnTitle:attrOk otherBtnTitles:attrOtherTitles isVertical:isVertical];
    }
    return  self;
}

- (instancetype)initLoading
{
    self = [super init];
    if (self) {
        [self setup];
        [self setMainViewActions];
        UIImageView * imgView = [self imageViewWithGifName:@"loading" animationDuration:2];
        imgView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.3];
        [_extendedContainer addSubview:imgView];
        [imgView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(120, 90));
            make.edges.mas_equalTo(_extendedContainer);
        }];
        [imgView startAnimating];
    }
    return self;
}
#pragma mark - action
- (void)tapBgView:(UITapGestureRecognizer *)tapGR{
    if (self.willDismissAlertViewTapBgViewBlock) {
        if ([self willDismissAlertViewTapBgViewBlock]) {
            [self dismissWithAnimated:YES];
        }else{
            
        }
    }else{
        [self dismissWithAnimated:YES];
    }
    
}
- (void)tapBtn:(UIButton *)btn{

   
    if (self.willDismissAlertViewTapBtnBlock(btn)) {
                [self dismissWithAnimated:YES];
    }else{
        [self dismissWithAnimated:YES];
    }
}
#pragma mark - private 以后整理成单独类，catagory
- (NSMutableAttributedString *)attrStringWithString:(NSString *)string color:(UIColor *)color font:(UIFont *)font{
        return [[NSMutableAttributedString alloc]initWithString:string attributes:@{
                                                                          NSForegroundColorAttributeName:color,                                                                                    NSFontAttributeName:font
                                                                          
                                                                          }];
}



-(UIImageView *)imageViewWithGifName:(NSString *)gifName animationDuration:(NSTimeInterval)animationDuration{
    UIImageView * imageView = [UIImageView new];
    if (imageView) {
        NSURL *fileUrl = [[NSBundle mainBundle] URLForResource:gifName withExtension:@"gif"]; //加载GIF图片
        CGImageSourceRef gifSource = CGImageSourceCreateWithURL((CFURLRef) fileUrl, NULL);           //将GIF图片转换成对应的图片源
        size_t frameCout = CGImageSourceGetCount(gifSource);                                         //获取其中图片源个数，即由多少帧图片组成
        NSMutableArray *frames = [[NSMutableArray alloc] init];                                      //定义数组存储拆分出来的图片
        for (size_t i = 0; i < frameCout; i++) {
            CGImageRef imageRef = CGImageSourceCreateImageAtIndex(gifSource, i, NULL); //从GIF图片中取出源图片
            //            UIImage *imageName = [UIImage imageWithCGImage:imageRef];                  //将图片源转换成UIimageView能使用的图片源
            UIImage *imageName = [UIImage imageWithCGImage:imageRef scale:2 orientation:UIImageOrientationUp];
            //            NSLog(@"scale %f", imageName.scale);
            
            [frames addObject:imageName];                                              //将图片加入数组中
            CGImageRelease(imageRef);
        }
        
        imageView.animationImages = frames; //将图片数组加入UIImageView动画数组中
        imageView.animationDuration = animationDuration; //每次动画时长
        //        [self startAnimating];         //开启动画，此处没有调用播放次数接口，UIImageView默认播放次数为无限次，故这里不做处理
        
    }
    return imageView;
}


@end
